package ca.etsmtl.utilities;


import java.io.File;
import java.util.ArrayList;

/**
 * Utility methods that contains repeating and quite boring methods that help with the console output.
 * @author Kevin Barron <kevin.barron.1@ens.etsmtl.ca>
 * @author Maxime Caumartin <maxime.caumartin.1@ens.etsmtl.ca>
 */
public class ConsoleUtilities
{
	private static final String[] help = new String[] {"-h","--help"};
	private static final String[] debug = new String[] {"-d","--debug"};
	
	private static boolean debugEnabled = false;
	
	/**
	 * Returns if the application should run in debug mode or not.
	 * @return The debug status
	 */
	public static boolean debug()
	{
		return debugEnabled;
	}
	
	public static void debug(String msg)
	{
		if (debugEnabled)
			System.err.println(msg);
	}
	
	public static void debugP(String point,String msg)
	{
		if (debug())
			debug(msg);
		else
			System.out.print(point);
	}
	
	public static void printUsage(String applicationName, String helpText,String... filelist)
	{
		StringBuilder b = new StringBuilder();
		for (int i =0;i<filelist.length;i++)
		{
			if ( filelist[i].equals("..."))
				b.append(filelist[i]);
			else
				b.append("[").append(filelist[i]).append("] ");
		}
		
		System.out.println(String.format("Usage : %1$s %3$s <options>\n%2$s\nOptions : \n -d|--debug : More verbosity\n -h|--help : This help message",applicationName,helpText,b));
	}
	
	public static String[] parseParameters(String[] args)
	{
		if (args == null) // Failsafe if the calling array is null
			return null;
		
		ArrayList<String> parameters = new ArrayList<String>();
		
		for (String arg : args)
		{
			if (isHelpDemand(arg))
				return null;
			if (isDebugAsked(arg))
			{
				debugEnabled = true;
				continue;
			}
			parameters.add(arg);
		}
		return parameters.toArray(new String[parameters.size()]);
	}
	
	public static boolean isHelpDemand(String parameter)
	{
		return parameter.equals(help[0]) || parameter.equals(help[1]);
	}
	
	public static boolean isDebugAsked(String parameter)
	{
		return parameter.equals(debug[0]) || parameter.equals(debug[1]);
	}
	
	public static boolean fileExists(String filepath)
	{
		return new File(filepath).isFile();
	}
}